#!/usr/bin/env ruby
#
# Generate a Ruby version of an RDFa vocabulary to be directly accessible from RDF::RDFa::Vocabulary
require 'rubygems'
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), "..", 'lib')))
require 'linkeddata'
require 'getoptlong'
require 'open-uri'

def help
  puts "Usage: #{$0} [options] file-or-uri ..."
  puts "Options:"
  puts "      --dump:               Dump raw output, otherwise serialize to Ruby"
  puts "      --debug:              Display detailed debug output"
  puts "      --verbose:            Verbose processing"
  puts "      --uri URI:            Use URI as context, rather than original filename"
  puts "      --output:             Write to file"
  puts "      --help,-?:            This message"
  exit(0)
end

module RDF
  class URI
    def dump; "RDF::URI('#{self}')"; end
  end
  
  class Node
    def dump; "RDF::Node.new('#{id}')"; end
  end
  
  class Literal
    def dump
      "RDF::Literal('#{value}'" +
        (", datatype: #{datatype.dump}" if datatype).to_s +
        (", language: :#{language}" if language).to_s +
        ")"
    end
  end
  
  class Statement
    def dump
      "RDF::Statement.new(#{subject.dump}, #{predicate.dump}, #{object.dump}, context: #{context.dump})"
    end
  end
  
  class RDFXML::Format
    # Add mime-type for text/xml
    content_type     'text/xml', extension: :xml
  end
end

dump = false
output = STDOUT
uri = nil

opts = GetoptLong.new(
  ["--debug", GetoptLong::NO_ARGUMENT],
  ["--dump", GetoptLong::NO_ARGUMENT],
  ["--output", "-o", GetoptLong::REQUIRED_ARGUMENT],
  ["--verbose", GetoptLong::NO_ARGUMENT],
  ["--uri",     GetoptLong::REQUIRED_ARGUMENT],
  ["--help", "-?", GetoptLong::NO_ARGUMENT]
)
opts.each do |opt, arg|
  case opt
  when '--verbose'  then $verbose = true
  when '--debug'    then ::RDF::RDFa::debug = true
  when '--dump'     then dump = true
  when '--output'   then output = File.open(arg, "w")
  when '--uri'      then uri = RDF::URI(arg)
  when '--help'     then help
  end
end

help if ARGV.empty?

ARGV.each do |file|
  uri ||= RDF::URI(file)
  graph = RDF::Graph.new
  RDF::Graph.load(file).each do |statement|
    next unless [RDF::RDFS.subClassOf, RDF::RDFS.subPropertyOf].include?(statement.predicate)
    graph << statement
  end
  
  next unless graph.size > 0

  if dump
    puts g.dump(:ttl)
  else
    preceeding = '    '
    output.puts  <<START
# This file is automatically generated by #{__FILE__}
# RDFa vocabulary for #{uri} loaded from #{file}
require 'rdf/rdfa/expansion'

module RDF::RDFa::Expansion
  [
START

    graph.each do |statement|
      statement.context = uri
      output.puts %{#{preceeding}#{statement.dump},}
    end
    
    output.puts <<END
  ].each {|st| COOKED_VOCAB_STATEMENTS << st }
end
END

  end
end
